package com.ujiuye.controller;


import com.sun.org.apache.xml.internal.resolver.tools.ResolvingParser;
import com.ujiuye.config.MessageConstant;
import com.ujiuye.config.PageResult;
import com.ujiuye.config.QueryPageBean;
import com.ujiuye.config.Result;
import com.ujiuye.pojo.User;
import com.ujiuye.service.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户 ----系统管理员 前端控制器
 * </p>
 *
 * @author zs
 * @since 2021-07-05
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private IUserService userService;

    @PostMapping("list")
    public PageResult list(@RequestBody QueryPageBean queryPageBean){
        try {
            return userService.userList(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("save")
    public Result save(@RequestBody User user){
        try {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            userService.save(user);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.ADD_USER_FAIL);
        }
    }
    @GetMapping("/{id}")
    public Result  getById(@PathVariable("id") int id){
        try {
            User user = userService.getById(id);
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }

    }

    @PostMapping("update")
    public Result update(@RequestBody User user){
        try {
            userService.updateById(user);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") int id){
        try {
            userService.removeById(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }

}

